package algorithm.middle;

/**
 * 设计循环队列
 * https://leetcode.cn/problems/design-circular-queue/
 */
class MyCircularQueue {

    int[] arr;
    int head;
    //始终保持为空。指定为最后一个元素的后一个格子。
    int tail;

    public MyCircularQueue(int k) {
        arr = new int[k + 1];
        head = 0;
        tail = 0;
    }

    public boolean enQueue(int value) {
        if (isFull()) return false;
        //对列没有满的情况下，往tail位置添加一个元素
        arr[tail] = value;
        tail = (tail + 1) % arr.length;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) return false;
        head = (head + 1) % arr.length;
        return true;
    }

    public int Front() {
        if (isEmpty()) return -1;
        return arr[head];
    }

    public int Rear() {
        if (isEmpty()) return -1;
        return arr[(tail + arr.length - 1) % arr.length];
    }

    public boolean isEmpty() {
        return tail == head;
    }

    public boolean isFull() {
        return (tail + 1) % arr.length == head;
    }

    public static void main(String[] args) {
        MyCircularQueue myCircularQueue = new MyCircularQueue(3);
        myCircularQueue.enQueue(1);
        myCircularQueue.enQueue(2);
        myCircularQueue.enQueue(3);
        myCircularQueue.enQueue(4);
    }
}
